package net.zjitc.dao.impl;

import net.zjitc.dao.ProductDao;
import net.zjitc.pojo.Product;
import net.zjitc.utils.PageBean;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017/11/22.
 */
public class ProductDaoImpl implements ProductDao {
    public PageBean<Product> findPageBean(int page, int pageSize) {
        //pageBean的参数都是什么时候设置进去的，一定要设置，要不页面取不到
        PageBean<Product> pageBean = new PageBean<Product>();
        pageBean.setPage(page);
        pageBean.setPageSize(pageSize);
        //查总条数
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select count(*) from product";
        //要符合条件的
        String ssql = "select * from product order by pid limit ?,?";
        try {
            Number num = (Number) runner.query(sql,new ScalarHandler());
            int count = num.intValue();
            pageBean.setCount(count);
            List<Product>  list = (List<Product>) runner.query(ssql,new BeanListHandler(Product.class),(page-1)*pageSize,pageSize);
            pageBean.setPageList(list);
            return pageBean;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int insert(Product product) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "insert into product(pname,market_price,shop_price,image,pdesc,is_hot,pdate,csid) value(?,?,?,?,?,?,?,?)";
        try {
            int count = runner.update(sql,product.getPname(),product.getMarket_price(),product.getShop_price(),
                    product.getImage(),product.getPdesc(),product.getIs_hot(),product.getPdate(),product.getCategorySecond().getCsid());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
